package com.mrzhou.auth.service;

import com.mrzhou.auth.constant.AuthConstant;
import com.mrzhou.auth.exception.IntegrationException;
import com.mrzhou.common.entity.system.UserInfo;
import com.mrzhou.core.tool.utils.Func;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;

import java.util.Collection;

/**
 *  SpringSecurity的User扩展
 */
@Getter
@Setter
public class CloudUserDetails extends User {

    /** 用户id */
    private Long userId;

    /** 用户账号 */
    private String account;

    /** 用户姓名 */
    private String name;

    /** 用户真实姓名 */
    private String realName;

    /** 用户头像 */
    private String avatar;

    /** 用户手机 */
    private String phone;

    /** 用户邮箱 */
    private String email;

    /** 角色名称 */
    private String roleName;

    /** 登录时使用的登录类型 */
    private String authType;

    public CloudUserDetails(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired,
                            boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    }

    public static CloudUserDetails createCloudUserDetails(UserInfo userInfo) throws IntegrationException {
        com.mrzhou.common.entity.system.User user = userInfo.getUser();

        if(Func.isListEmpty(userInfo.getRoleAlias())) {
            throw new IntegrationException("用户权限为空！");
        }

        CloudUserDetails details = new CloudUserDetails(user.getAccount(), AuthConstant.ENCRYPT+user.getPassword(),
                true, true,
                true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(userInfo.getRoleAlias())));
        details.setUserId(user.getId());
        details.setAccount(user.getAccount());
        details.setName(user.getNickName());
        details.setRealName(user.getRealName());
        details.setAvatar(user.getAvatar());
        details.setPhone(user.getPhone());
        details.setEmail(user.getEmail());
        details.setRoleName(Func.join(userInfo.getRoleAlias()));;
        return details;
    }

}


